#ifndef __CONFIG_H__
#define __CONFIG_H__
#include "util.hpp"
#include <mutex>

namespace Cloud
{
    #define CONFIG_FILE "./Cloud.conf"
    class Config
    {
    private:
        Config(){
            if(ReadConfigFile() == false)
            {
                std::cout << "配置文件初始化失败\n";
                exit(-1);
            }
        }
        static Config *_instance;
        static std::mutex _mutex;
    private:
        int _hot_time;//热点时间
        int _server_port;//服务器端口号
        std::string _server_ip;//服务器IP
        std::string _download_prefix;//下载前缀
        std::string _packfile_suffix;//压缩包后缀
        std::string _pack_dir;//压缩包存放路径
        std::string _back_dir;//备份文件存放路径
        std::string _backup_file;//备份文件信息

        bool ReadConfigFile()//读取配置文件 
        {
            FileUtil file(CONFIG_FILE);
            std::string body;
            if(file.GetContent(&body) == false)
            {
                std::cout << "配置文件读取失败\n";
                return false;
            }
            Json::Value root;
            if(JsonUtil::UnSerialize(body, &root) == false)
            {
                std::cout << "反序列化配置文件失败\n";
                return false;
            }
            _hot_time = root["hot_time"].asInt64();
            _server_port = root["server_port"].asInt64();
            _server_ip = root["server_ip"].asString();
            _download_prefix = root["download_prefix"].asString();
            _packfile_suffix = root["packfile_suffix"].asString();
            _pack_dir = root["pack_dir"].asString();
            _back_dir = root["back_dir"].asString();
            _backup_file = root["backup_file"].asString();
            return true;
        }
    public:
        static Config* GetInstance()
        {
            if(_instance == nullptr)//减少锁冲突
            {
                std::unique_lock<std::mutex> lock(_mutex);
                if(_instance == nullptr)//为了new一个单例类
                {
                    _instance = new Config();
                }
            }
            return _instance;
        }
        int GetHotTime() { return _hot_time; }
        int GetServerPort() { return _server_port; }
        std::string GetServerIp() { return _server_ip; }
        std::string GetDownLoadPrefix() { return _download_prefix; }
        std::string GetPackFileSuffix() { return _packfile_suffix; }
        std::string GetPackDir() { return _pack_dir; }
        std::string GetBackDir() { return _back_dir; }
        std::string GetBackUpFile() { return _backup_file; }
    };
    Config* Config::_instance = nullptr;
    std::mutex Config::_mutex;
}
#endif